import React, { useState, useEffect } from "react";
import { useParams, useHistory } from "react-router-dom";
import "./home.scss";
import "antd/dist/antd.css";
import axios from "axios";
import "antd/dist/antd.css";
import { BaseUrl } from "../manger/network";
import tokenManager from "../manger/tokenManager";
import { post } from "../manger/network";
import {
  Layout,
  Menu,
  Button,
  Input,
  Form,
  Upload,
  message,
  Pagination,
  List,
  Image,
  Card,
} from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { DesktopOutlined, TeamOutlined } from "@ant-design/icons";
const FormItem = Form.Item;
const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;
const { Meta } = Card;

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
}

export default function Home() {
  const [index, setIndex] = useState(1);
  const [token, setToken] = useState(null);
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const [realUrl, setRealUrl] = useState(null);

  const [goodsName, setGoodsName] = useState("");
  const [goodsDesc, setGoodsDesc] = useState("");
  const [goodsPrice, setGoodsPrice] = useState("");
  const [goodsCount, setGoodsCount] = useState(1);

  const [totalCount, setTotalCount] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [data, setData] = useState([]);

  const [totalAllCount, setTotalAllCount] = useState(0);
  const [currentAllPage, setCurrentAllPage] = useState(1);
  const [alldata, setAllData] = useState([]);

  const history = useHistory();
  useEffect(() => {
    let token = tokenManager.getToken();
    setToken(token);

    post("/getgoods", {
      pageNum: currentPage,
      pageSize: 20,
    })
      .then((resopnse) => {
        if (resopnse.code == 0 && resopnse.data && resopnse.data.list) {
          setData(resopnse.data.list);
          setTotalCount(resopnse.data.totalSize);
        }
      })
      .catch((err) => {});

    post("/getallgoods", {
      pageNum: currentAllPage,
      pageSize: 20,
    })
      .then((resopnse) => {
        if (resopnse.code == 0 && resopnse.data && resopnse.data.list) {
          setAllData(resopnse.data.list);
          setTotalAllCount(resopnse.data.totalSize);
        }
      })
      .catch((err) => {});
  }, []);
  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(e) => setCollapsed(e)}
      >
        <div className="logo" />
        <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
          <SubMenu key="sub1" icon={<DesktopOutlined />} title="商品">
            {token ? (
              <Menu.Item onClick={() => setIndex(0)} key="0">
                新增商品
              </Menu.Item>
            ) : null}
            <Menu.Item
              onClick={() => {
                setIndex(1);
                setCurrentPage(1);
                post("/getgoods", {
                  pageNum: currentPage,
                  pageSize: 20,
                })
                  .then((resopnse) => {
                    if (
                      resopnse.code == 0 &&
                      resopnse.data &&
                      resopnse.data.list
                    ) {
                      setData(resopnse.data.list);
                      setTotalCount(resopnse.data.totalSize);
                    }
                  })
                  .catch((err) => {});
              }}
              key="1"
            >
              商品列表
            </Menu.Item>
            {token ? (
              <Menu.Item
                onClick={() => {
                  setIndex(2);
                  setCurrentAllPage(1);
                  post("/getallgoods", {
                    pageNum: currentAllPage,
                    pageSize: 20,
                  })
                    .then((resopnse) => {
                      if (
                        resopnse.code == 0 &&
                        resopnse.data &&
                        resopnse.data.list
                      ) {
                        setAllData(resopnse.data.list);
                        setTotalAllCount(resopnse.data.totalSize);
                      }
                    })
                    .catch((err) => {});
                }}
                key="2"
              >
                商品管理
              </Menu.Item>
            ) : null}
          </SubMenu>
          <SubMenu
            key="sub2"
            icon={<TeamOutlined />}
            onClick={() => setIndex(0)}
            title="用户"
          >
            <Menu.Item
              onClick={() => {
                if (token && token.length > 0) {
                  tokenManager.clearToken();
                  setToken(null);
                } else {
                  history.push("/login");
                }
              }}
              key="2"
            >
              {token && token.length > 0 ? "登出" : "登录"}
            </Menu.Item>
          </SubMenu>
        </Menu>
      </Sider>
      <Layout className="site-layout">
        <Header className="site" style={{ padding: 0 }}>
          <Button
            onClick={() => {
              if (token && token.length > 0) {
                tokenManager.clearToken();
                setToken(null);
              } else {
                history.push("/login");
              }
            }}
            className="loginBtn"
          >
            {token && token.length > 0 ? "登出" : "登录"}
          </Button>
        </Header>
        {index == 0 ? (
          <Content style={{ margin: "0 16px" }}>
            <div className="siteView" style={{ padding: 24, minHeight: 360 }}>
              <div className="whiteView">
                <Form className="form">
                  <FormItem label="商品名称:" className="formitem">
                    <Input
                      placeholder="请输入商品名称"
                      value={goodsName}
                      onChange={(e) => {
                        setGoodsName(e.target.value);
                      }}
                      maxLength={20}
                    />
                  </FormItem>
                  <FormItem label="商品描述:" className="formitem">
                    <Input
                      value={goodsDesc}
                      placeholder="请输入商品描述"
                      onChange={(e) => {
                        setGoodsDesc(e.target.value);
                      }}
                      maxLength={50}
                    />
                  </FormItem>
                  <FormItem label="商品价格:" className="formitem">
                    <Input
                      value={goodsPrice}
                      placeholder="请输入商品价格"
                      onChange={(e) => {
                        setGoodsPrice(e.target.value);
                      }}
                      maxLength={8}
                    />
                  </FormItem>
                  <FormItem label="商品数量:" className="formitem">
                    <Input
                      value={goodsCount}
                      placeholder="请输入商品数量"
                      onChange={(e) => {
                        setGoodsCount(e.target.value);
                      }}
                      maxLength={6}
                    />
                  </FormItem>
                  <Upload
                    name="file"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action={`${BaseUrl}/upload`}
                    beforeUpload={beforeUpload}
                    onChange={(info) => {
                      if (info.file.status === "uploading") {
                        setLoading(true);
                        return;
                      }
                      if (info.file.status === "done") {
                        getBase64(info.file.originFileObj, (imageUrl) => {
                          setLoading(false);
                          console.log("imageUrl == ", imageUrl);
                          setImageUrl(imageUrl);
                          setRealUrl(info.file.response.url);
                        });
                      }
                    }}
                  >
                    {imageUrl ? (
                      <img
                        src={imageUrl}
                        alt="avatar"
                        style={{ width: "100%" }}
                      />
                    ) : (
                      <div>
                        {loading ? <LoadingOutlined /> : <PlusOutlined />}
                        <div style={{ marginTop: 8 }}>上传图片</div>
                      </div>
                    )}
                  </Upload>
                  <Button
                    type="primary"
                    className="confirmBtn"
                    onClick={() => {
                      if (goodsName.length == 0) {
                        message.error("请输入商品名称");
                        return;
                      }
                      if (goodsPrice.length == 0) {
                        message.error("请输入商品价格");
                        return;
                      }
                      if (!/^\d+$/.test(goodsCount)) {
                        message.error("请输入正确的商品数量");
                        return;
                      }
                      post("/addgoods", {
                        name: goodsName,
                        desc: goodsDesc,
                        price: goodsPrice,
                        url: realUrl,
                        count: goodsCount,
                      })
                        .then((response) => {
                          if (response.code == 0) {
                            message.success("添加商品成功");
                            setGoodsName("");
                            setGoodsPrice("");
                            setGoodsDesc("");
                            setGoodsCount("1");
                          } else {
                            message.error(response.msg);
                          }
                        })
                        .catch((err) => {
                          message.error(err.message);
                          console.log(err);
                        });
                    }}
                  >
                    确认
                  </Button>
                </Form>
              </div>
            </div>
          </Content>
        ) : index == 1 ? (
          <Content style={{ margin: "0 16px" }}>
            <div className="goodsList" style={{ padding: 24, minHeight: 360 }}>
              <List
                grid={{ gutter: 16, xs: 1 }}
                dataSource={data}
                renderItem={(item) => {
                  return (
                    <List.Item>
                      <Card
                        hoverable
                        bordered={true}
                        style={{ width: 300 }}
                        cover={<Image src={BaseUrl + "/" + item.image} />}
                      >
                        <Meta
                          title={`${item.name}(${item.description})`}
                          description={`价格￥:${item.price}`}
                        />
                        <Meta description={`数量:${item.count}`} />
                      </Card>
                    </List.Item>
                  );
                }}
              />
              <Pagination
                simple
                current={currentPage}
                onChange={(page, pageSize) => {
                  setCurrentPage(page);
                  post("/getgoods", {
                    pageNum: page,
                    pageSize: pageSize,
                  })
                    .then((resopnse) => {
                      if (
                        resopnse.code == 0 &&
                        resopnse.data &&
                        resopnse.data.list
                      ) {
                        setData(resopnse.data.list);
                        setTotalCount(resopnse.data.totalSize);
                      }
                    })
                    .catch((err) => {});
                }}
                defaultPageSize={20}
                defaultCurrent={1}
                total={totalCount}
              />
            </div>
          </Content>
        ) : (
          <Content style={{ margin: "0 16px" }}>
            <div className="goodsList" style={{ padding: 24, minHeight: 360 }}>
              <List
                grid={{ gutter: 16, xs: 1 }}
                dataSource={alldata}
                renderItem={(item) => {
                  return (
                    <List.Item
                      onClick={() => {
                        history.push({
                          pathname: "/editGoods",
                          state: item,
                        });
                      }}
                    >
                      <Card
                        hoverable
                        bordered={true}
                        style={{ width: 300 }}
                        cover={
                          <Image
                            preview={false}
                            src={BaseUrl + "/" + item.image}
                          />
                        }
                      >
                        <Meta
                          title={`${item.name}(${item.description})`}
                          description={`价格￥:${item.price}`}
                        />
                        <Meta description={`数量:${item.count}`} />
                      </Card>
                    </List.Item>
                  );
                }}
              />
              <Pagination
                simple
                current={currentAllPage}
                onChange={(page, pageSize) => {
                  setCurrentAllPage(page);
                  post("/getallgoods", {
                    pageNum: page,
                    pageSize: pageSize,
                  })
                    .then((resopnse) => {
                      if (
                        resopnse.code == 0 &&
                        resopnse.data &&
                        resopnse.data.list
                      ) {
                        setAllData(resopnse.data.list);
                        setTotalAllCount(resopnse.data.totalSize);
                      }
                    })
                    .catch((err) => {});
                }}
                defaultPageSize={20}
                defaultCurrent={1}
                total={totalAllCount}
              />
            </div>
          </Content>
        )}
        <Footer style={{ textAlign: "center" }}>©2021 Created by Conan</Footer>
      </Layout>
    </Layout>
  );
}
